#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
稳定的瀑布流显示组件
使用同步方式加载图片，但添加更好的错误处理
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, 
                             QLabel, QScrollArea, QFrame, QPushButton, QSpinBox)
from PyQt5.QtCore import Qt, pyqtSignal, QTimer
from PyQt5.QtGui import QPixmap, QFont, QPalette, QColor
import requests
import time
from urllib.parse import urlparse

class StableImageItem(QFrame):
    """稳定的图片项"""
    
    clicked = pyqtSignal(int)  # 点击信号，传递索引
    
    def __init__(self, index, image_info, parent=None):
        super().__init__(parent)
        self.index = index
        self.image_info = image_info
        self.is_selected = False
        self.pixmap = None
        self.loading_timer = QTimer()
        self.loading_timer.timeout.connect(self.load_image_delayed)
        
        self.setup_ui()
        # 延迟加载图片，避免同时加载太多图片
        self.loading_timer.start(index * 100)  # 每个图片延迟100ms
        
    def setup_ui(self):
        """设置UI"""
        self.setFixedSize(200, 200)
        self.setFrameStyle(QFrame.Box)
        self.setLineWidth(2)
        self.setStyleSheet("""
            QFrame {
                background-color: #f0f0f0;
                border: 2px solid #cccccc;
                border-radius: 8px;
            }
            QFrame:hover {
                border-color: #0078d4;
            }
        """)
        
        # 创建布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(5, 5, 5, 5)
        
        # 图片标签
        self.image_label = QLabel("加载中...")
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setFixedSize(190, 150)
        self.image_label.setStyleSheet("""
            QLabel {
                background-color: #f8f8f8;
                border: 1px solid #ddd;
                border-radius: 4px;
                color: #666;
                font-size: 12px;
            }
        """)
        layout.addWidget(self.image_label)
        
        # 标题标签
        self.title_label = QLabel()
        self.title_label.setAlignment(Qt.AlignCenter)
        self.title_label.setWordWrap(True)
        self.title_label.setMaximumHeight(40)
        self.title_label.setStyleSheet("font-size: 10px; color: #666;")
        layout.addWidget(self.title_label)
        
        # 设置标题
        title = self.image_info.get('title', '未知图片')
        if len(title) > 30:
            title = title[:30] + '...'
        self.title_label.setText(title)
        
    def load_image_delayed(self):
        """延迟加载图片"""
        self.loading_timer.stop()
        self.load_image()
        
    def load_image(self):
        """同步加载图片"""
        try:
            url = (self.image_info.get('thumbnail_url') or 
                   self.image_info.get('original_url') or 
                   self.image_info.get('thumbnail') or 
                   self.image_info.get('url'))
            if not url:
                self.show_placeholder("无图片URL")
                return
                
            print(f"🖼️ [StableImageItem] 开始加载图片 {self.index}: {url[:50]}...")
            
            # 设置请求头
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Referer': 'https://image.baidu.com',
                'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
                'Accept-Encoding': 'gzip, deflate',
                'Connection': 'keep-alive'
            }
            
            # 同步请求图片，设置较短的超时时间
            response = requests.get(url, headers=headers, timeout=5)
            response.raise_for_status()
            
            print(f"✅ [StableImageItem] 图片 {self.index} 加载成功，大小: {len(response.content)} bytes")
            
            # 创建QPixmap
            pixmap = QPixmap()
            if pixmap.loadFromData(response.content):
                # 缩放图片
                scaled_pixmap = pixmap.scaled(190, 150, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                self.image_label.setPixmap(scaled_pixmap)
                self.pixmap = scaled_pixmap
                print(f"✅ [StableImageItem] 图片 {self.index} 显示成功")
            else:
                print(f"❌ [StableImageItem] 图片 {self.index} 格式不支持")
                self.show_placeholder("格式不支持")
                
        except requests.exceptions.Timeout:
            print(f"⏰ [StableImageItem] 图片 {self.index} 加载超时")
            self.show_placeholder("加载超时")
        except requests.exceptions.RequestException as e:
            print(f"🌐 [StableImageItem] 图片 {self.index} 网络错误: {e}")
            self.show_placeholder("网络错误")
        except Exception as e:
            print(f"❌ [StableImageItem] 图片 {self.index} 加载失败: {e}")
            self.show_placeholder("加载失败")
    
    def show_placeholder(self, reason="加载失败"):
        """显示占位符"""
        self.image_label.setText(f"图片\n{reason}")
        self.image_label.setStyleSheet("""
            QLabel {
                background-color: #f5f5f5;
                border: 1px solid #ddd;
                border-radius: 4px;
                color: #999;
                font-size: 12px;
            }
        """)
    
    def mousePressEvent(self, event):
        """鼠标点击事件"""
        if event.button() == Qt.LeftButton:
            self.clicked.emit(self.index)
    
    def set_selected(self, selected):
        """设置选中状态"""
        self.is_selected = selected
        if selected:
            self.setStyleSheet("""
                QFrame {
                    background-color: #f0f0f0;
                    border: 3px solid #ff6600;
                    border-radius: 8px;
                }
            """)
        else:
            self.setStyleSheet("""
                QFrame {
                    background-color: #f0f0f0;
                    border: 2px solid #cccccc;
                    border-radius: 8px;
                }
                QFrame:hover {
                    border-color: #0078d4;
                }
            """)

class StableWaterfallDisplay(QWidget):
    """稳定的瀑布流显示组件"""
    
    selection_changed = pyqtSignal(list)  # 选择变化信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.images = []
        self.selected_indices = set()
        self.image_items = []
        
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI"""
        self.setMinimumSize(800, 600)
        
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(10, 10, 10, 10)
        
        # 控制面板
        control_panel = QHBoxLayout()
        
        # 列数设置
        control_panel.addWidget(QLabel("列数:"))
        self.columns_spinbox = QSpinBox()
        self.columns_spinbox.setRange(1, 8)
        self.columns_spinbox.setValue(4)
        self.columns_spinbox.valueChanged.connect(self.update_display)
        control_panel.addWidget(self.columns_spinbox)
        
        control_panel.addStretch()
        
        # 全选/取消全选按钮
        self.select_all_btn = QPushButton("全选")
        self.select_all_btn.clicked.connect(self.select_all)
        control_panel.addWidget(self.select_all_btn)
        
        self.clear_selection_btn = QPushButton("取消全选")
        self.clear_selection_btn.clicked.connect(self.clear_selection)
        control_panel.addWidget(self.clear_selection_btn)
        
        main_layout.addLayout(control_panel)
        
        # 滚动区域
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        
        # 内容widget
        self.content_widget = QWidget()
        self.scroll_area.setWidget(self.content_widget)
        
        # 网格布局
        self.grid_layout = QGridLayout(self.content_widget)
        self.grid_layout.setSpacing(10)
        
        main_layout.addWidget(self.scroll_area)
        
        # 状态栏
        self.status_label = QLabel("就绪")
        self.status_label.setStyleSheet("color: #666; font-size: 12px;")
        main_layout.addWidget(self.status_label)
        
    def add_images(self, images):
        """添加图片"""
        print(f"🖼️ [StableWaterfall] 开始添加 {len(images)} 张图片")
        
        self.images.extend(images)
        self.update_display()
        
        print(f"✅ [StableWaterfall] 添加完成，总共 {len(self.images)} 张图片")
        
    def clear_images(self):
        """清空图片"""
        print("🧹 [StableWaterfall] 清空所有图片")
        
        # 清空布局
        for i in reversed(range(self.grid_layout.count())):
            child = self.grid_layout.itemAt(i).widget()
            if child:
                child.setParent(None)
        
        self.images.clear()
        self.image_items.clear()
        self.selected_indices.clear()
        
        self.status_label.setText("已清空")
        
    def update_display(self):
        """更新显示"""
        print(f"🔄 [StableWaterfall] 开始更新显示，图片数量: {len(self.images)}")
        
        if not self.images:
            self.status_label.setText("没有图片")
            return
        
        # 清空现有布局
        for i in reversed(range(self.grid_layout.count())):
            child = self.grid_layout.itemAt(i).widget()
            if child:
                child.setParent(None)
        
        self.image_items.clear()
        
        # 计算布局
        columns = self.columns_spinbox.value()
        rows = (len(self.images) + columns - 1) // columns
        
        print(f"📐 [StableWaterfall] 布局: {rows} 行 x {columns} 列")
        
        # 创建图片项
        for i, image_info in enumerate(self.images):
            row = i // columns
            col = i % columns
            
            # 创建图片项
            image_item = StableImageItem(i, image_info)
            image_item.clicked.connect(self.on_image_clicked)
            
            # 添加到布局
            self.grid_layout.addWidget(image_item, row, col)
            self.image_items.append(image_item)
            
            print(f"🖼️ [StableWaterfall] 创建图片项 {i+1}: {image_info.get('title', '未知')[:30]}...")
        
        self.status_label.setText(f"显示 {len(self.images)} 张图片")
        print(f"✅ [StableWaterfall] 显示更新完成")
        
    def on_image_clicked(self, index):
        """图片点击事件"""
        if index in self.selected_indices:
            self.selected_indices.remove(index)
            self.image_items[index].set_selected(False)
        else:
            self.selected_indices.add(index)
            self.image_items[index].set_selected(True)
        
        self.selection_changed.emit(self.get_selected_images())
        
    def select_all(self):
        """全选"""
        self.selected_indices = set(range(len(self.images)))
        for i, item in enumerate(self.image_items):
            item.set_selected(True)
        self.selection_changed.emit(self.get_selected_images())
        
    def clear_selection(self):
        """取消全选"""
        self.selected_indices.clear()
        for item in self.image_items:
            item.set_selected(False)
        self.selection_changed.emit(self.get_selected_images())
        
    def get_selected_images(self):
        """获取选中的图片"""
        return [self.images[i] for i in self.selected_indices]
        
    def get_selected_indices(self):
        """获取选中的索引"""
        return list(self.selected_indices)
